package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.model.LoginModel;
import com.bishe.pojo.Student;
import com.bishe.mapper.StudentDao;
import com.bishe.pojo.Teacher;
import com.bishe.query.StudentQuery;
import com.bishe.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.util.EcoBootException;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.bishe.util.JobUtils.checkImgCode;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwx
 * @since 2022-04-14
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, Student> implements StudentService {


    @Override
    public LoginModel login(LoginModel loginModel) {
        if(loginModel ==null){
            throw new EcoBootException("登录失败!");
        }
        //验证 验证码
        checkImgCode(loginModel.getTxt());

        if (StrUtil.isEmpty(loginModel.getAccount())||StrUtil.isEmpty(loginModel.getPassWord())){
            throw new EcoBootException("用户名密码为空!");
        }

        String userName = loginModel.getAccount();
        String password = loginModel.getPassWord();
        Boolean rememberMe = loginModel.getRememberMe();
        if (rememberMe == null){
            rememberMe = false;
        }
        //根据用户名密码查找
        Student one = getOne(new LambdaQueryWrapper<Student>()
                        .eq(Student::getStudentNo, userName)
                        .eq(Student::getPassWord, password)
                ,false);

        if (one == null) {
            return null;
        }
        StpUtil.login(one.getId(),rememberMe);

        LoginModel model = new LoginModel();
        model.setUserName(one.getUserName());
        model.setSatoken(StpUtil.getTokenValue());

        return model;
    }

    @Override
    public IPage toPage(StudentQuery query) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(query.getUserName())){
            wrapper.like(Student::getUserName, query.getUserName());
        }

        wrapper.orderByDesc(Student::getCreateTime);

        return this.page(query.toPage(), wrapper);

    }

    @Override
    public void addOrUpdate(Student student) {
        Student one = this.getById(student);
        if (one == null){
            student.setId(StrUtil.uuid());
            student.setCreateTime(new Date());
            save(student);
            return;
        }
        updateById(one);
    }


}
